import { app, shell, BrowserWindow, ipcMain } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
import { reqAllTyre } from './api';
import { createOutputFile, hexToString, stringToHex } from './common';

export let mainWindow = null;
export let ipInfo = {
  address: '127.0.0.1', // 服务器地址
  cusPort: '8082', // MBSE服务器端口
  mrPort: '9200', // M-Require服务器端口
  tyPort: '8010', // 同元服务器端口
}

function createWindow() {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 1024,
    height: 768,
    show: false,
    autoHideMenuBar: true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })

  mainWindow.on('ready-to-show', () => {
    let inputStr = '5b,5d'
    // app未打包时，即为开发环境时
    if (!app.isPackaged) {
      mainWindow.webContents.openDevTools(); // 开启开发者工具

      // 向服务器请求数据(mock)
      ipInfo.address = '127.0.0.1';
      ipInfo.cusPort = '8082';
      ipInfo.mrPort = '9200';
      ipInfo.tyPort = '8010';

      inputStr = '[{"unit":"m","code":"QLJ_W","name":"机身长度","id":"131","type":"1","value":20400,"key":0},{"unit":"m","code":"ZZDZH","name":"机身长度","id":"131","type":"1","value":80.05,"key":0},{"unit":"m","code":"QZDZH","name":"机身长度","id":"131","type":"1","value":60.037,"key":0},{"unit":"m","code":"QLZH","name":"机身长度","id":"131","type":"1","value":91.207,"key":0},{"unit":"m","code":"ZLSD","name":"机身长度","id":"131","type":"1","value":300,"key":0}]';
      inputStr = stringToHex(inputStr); // 字符串转十六进制
      console.log('hex:', inputStr);
    }
    else {
      // mainWindow.webContents.openDevTools(); // 开启开发者工具
      if (process.argv.length > 1) {

        ipInfo.address = process.argv[1]; // ip地址
        ipInfo.cusPort = process.argv[2]; // MBSE服务器端口
        ipInfo.mrPort = process.argv[3]; // M-Require端口
        ipInfo.tyPort = process.argv[4]; // 同元端口

        inputStr = process.argv[5] || '[]';
      }
    }
    mainWindow.webContents.send('ipInfo', ipInfo);

    inputStr = hexToString(inputStr); // 十六禁止转字符串
    mainWindow.webContents.send('commandArgv', inputStr);

    mainWindow.show();
  })

  mainWindow.webContents.on('did-finish-load', () => {

  });

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url).then(() => {})
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL']).then(() => {})
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html')).then(() => {})
  }
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  // IPC test
  ipcMain.on('ping', () => console.log('pong'))
  ipcMain.handle('reqAllTyre', reqAllTyre); // 请求
  ipcMain.handle('createOutputFile', createOutputFile); // 请求

  createWindow()

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
